<template>
  <div class="dialog">
    <el-dialog :title="titleText + '批次二维码'" :visible.sync="showDialog" width="60%" :close-on-click-modal="false"
      @close="cancel">
      <el-form ref="formData" :model="formData" label-width="120px" :rules="rules" class="el-form">
        <el-form-item label="选择批次" prop="batchId" v-if="nowChanceStau == 'add'">
          <el-select class="w100p" filterable clearable v-model="formData.batchId" placeholder="请选择"
            @change="queryBatchFishVariety">
            <el-option v-for="item in batchList" :key="item.productionBatchId" :label="`${item.batchName}`"
              :value="item.batchId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="选择品种" prop="fishVarietyId" v-if="nowChanceStau == 'add'">
          <el-select v-model="formData.fishVarietyId" filterable clearable class="w100p" @change="getFishVarietyName">
            <el-option v-for="item, index in fishVarietyList" :key="index" :label="item.fishVarietyName"
              :value="item.fishVarietyId" />
          </el-select>
        </el-form-item>
        <el-form-item label="批次编号" v-if="nowChanceStau == 'edit'">
          <el-input v-model="formData.batchName" disabled></el-input>
        </el-form-item>
        <el-form-item label="品种名称" v-if="nowChanceStau == 'edit'">
          <el-input v-model="formData.fishVarietyName" disabled></el-input>
        </el-form-item>
        <el-form-item label="可见范围" prop="rangeList">
          <el-checkbox-group v-model="formData.rangeList" @change="handleCheckedCitiesChange">
            <el-checkbox v-for="city in checkInfoList" :label="city.value" :key="city.value">{{ city.label
              }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="基础内容">
          <div class="basicsList">
            <template v-for="element in draggableList">
              <div class="basics-item" v-if="showItem.indexOf(element.value) !== -1" :key="element.value">{{
      element.label }}</div>
            </template>
          </div>
        </el-form-item>
        <el-form-item label="阶段内容排序">
          <draggable class="w100p" v-model="draggableList" animation="1000" @start="onStart" @end="onEnd">
            <transition-group class="transition-group">
              <template v-for="element in draggableList">
                <div class="transition-group-item" v-if="showItem.indexOf(element.value) == -1" :key="element.value">
                  {{
      element.label }}</div>
              </template>
            </transition-group>
          </draggable>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button class="cancelbtn" @click="cancel()">取 消</el-button>
        <el-button type="primary" class="savebtn" @click="save('formData')">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

import pondStockingManagement from '@/api/production-management/pond-stocking-management.js';
import QRCodeMsgApi from "@/api/traceability/basicsInfo/QRCodeMsg";
import draggable from 'vuedraggable'

export default {
  name: '',
  components: {},
  props: {
    // 弹框名称
    titleText: {
      type: String,
      default: ""
    },
    nowChanceStau: {
      type: String,
      default: ""
    },
    show: {
      type: Boolean,
      default: false
    },
    batchList: {
      type: Array,
      default: false
    },
    checkInfoList: {
      type: Array,
      default: false
    },
    editObject: {
      type: [Object],
      default: () => {
        return {}
      }
    }
  },
  data() {
    return {
      fishVarietyList: [],
      showItem: ['1', '2', '3', '4'],
      drag: false,
      rules: {
        batchId: [
          { required: true, message: "请选择批次", trigger: ["change", "blur"] }
        ],
        rangeList: [
          { required: true, message: "请选择范围", trigger: ["change", "blur"] }
        ],
        fishVarietyId: [
          { required: true, message: "请选择品种", trigger: ["change", "blur"] }
        ],
      },
      formData: {},
      showDialog: this.show,
      draggableList: []
    };
  },
  components: {
    draggable,
  },
  created() {
  },
  mounted() {
  },
  watch: {
    show(v) {
      this.showDialog = v;
      v && this.initData();
      this.$refs['formData'] && this.$refs['formData'].resetFields();
    },
  },
  methods: {
    initData() {
      if (this.nowChanceStau == 'add') {
        this.formData = {
          rangeList: []
        },
          this.draggableList = []
      }
      console.log(this.editObject)
      if (this.nowChanceStau == 'edit') {
        if (this.editObject.range) {
          this.formData['rangeList'] = this.editObject.range.split(",")
        } else {
          this.formData['rangeList'] = []
        }
        this.handleCheckedCitiesChange(this.formData['rangeList'])
        console.log(this.editObject, this.formData)
        this.formData = { ...this.formData, ...this.editObject }
      }
    },
    onStart() {
      this.drag = true;
    },
    //拖拽结束事件
    onEnd(e) {
      console.log(this.draggableList)
      this.drag = false;
      let rangeList = [];
      this.draggableList.forEach(item => {
        rangeList.push(item.value)
      });
      this.formData.range = rangeList.join(',');
    },

    async queryBatchFishVariety(batchId) {
      let { data: fishVarietyList } = await pondStockingManagement.batchPondInfoList({ batchId });
      this.fishVarietyList = fishVarietyList;
    },
    getFishVarietyName(id) {
      let rut = this.fishVarietyList.find(item => { return item.fishVarietyId == id });
      this.$set(this.formData, 'fishVarietyName', rut.fishVarietyName)
    },
    isJSON(str) {
      if (typeof str == 'string') {
        try {
          var obj = JSON.parse(str);
          // 等于这个条件说明就是JSON字符串 会返回true
          if (typeof obj == 'object' && obj) {
            return true;
          } else {
            //不是就返回false
            return false;
          }
        } catch (e) {
          return false;
        }
      }
      return false;
    },
    // 多选
    handleCheckedCitiesChange(list) {
      this.draggableList = [];
      list.forEach(value => {
        let rut = this.checkInfoList.find(item => { return item.value == value })
        if (rut) {
          this.draggableList.push(rut)
        }
      })
      console.log(this.draggableList)
    },
    //保存
    save(formData) {
      this.$refs[formData].validate(valid => {
        if (valid) {
          let rangeList = [];
          this.draggableList.forEach(item => {
            rangeList.push(item.value)
          });
          this.formData.range = rangeList.join(',');
          if (this.nowChanceStau === "edit") {
            QRCodeMsgApi.edit(this.formData).then(res => {
              if (res.success === true) {
                this.$message.success("修改成功！");
                this.close()
              } else {
                this.$message.error(res.message);
              }
            });
          } else if (this.nowChanceStau === "add") {
            QRCodeMsgApi.add(this.formData).then(res => {
              if (res.success === true) {
                this.$message.success("添加成功！");
                this.close()
              } else {
                this.$message.error(res.message);
              }
            });
          }
        } else {
          return false;
        }
      });
    },
    close() {
      this.$emit("closeDialog");
    },
    cancel() {
      this.$emit("cancelDialog");
    }
  }
};
</script>

<style lang="scss" scoped>
.transition-group {
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start;
}

.basicsList {
  display: flex;
  justify-content: flex-start;
  flex-wrap: wrap;

  .basics-item {
    margin: 4px 10px;
    padding: 0 15px;
    border: 1px solid #0c5ca7;
    background: #d1e3ff;
    border-radius: 4px;
    color: #4e86c7;
    cursor: pointer;
  }
}

.transition-group-item {
  margin: 4px 10px;
  padding: 0 15px;
  border: 1px solid #4eafc7;
  background: #d8f7ff;
  border-radius: 4px;
  color: #4eafc7;
  cursor: pointer;

  &:hover {
    background: #90d3e4;
    color: #ffffff;
  }
}
</style>
